#include <iostream>
#include <string>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define N 2
#define NUM 1024

using namespace std;

//child
void Writer(int wfd)
{
    string s = "hello, I am child";
    pid_t self = getpid();
    int number = 0;

    char buffer[NUM];
    while(true)
    {
        //构建发送的字符串
        buffer[0] = 0;  //字符串清空,只是为了提醒阅读者，我把这个数组当成字符串了
        snprintf(buffer,sizeof(buffer),"%s-%d-%d",s.c_str(),self,number++);
        //cout<< buffer << endl;
        //发送给父进程
        write(wfd,buffer,strlen(buffer));
        // char ch='c';
        // write(wfd,&ch,1);
        // number++;
        // cout<< number <<endl;
        sleep(1);
    }
}

//father
void Reader(int rfd)
{
    //sleep(10);
    char buffer[NUM];

    while(true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd,buffer,sizeof(buffer));
        if(n > 0)
        {
            buffer[n] = 0; // 0 == '\0'
            cout << "father get a message[" << getpid()<< "]#"<< buffer << endl;
            
        }
        //sleep(5);
    }
}

int main()
{
    int pipefd[N] = {0};
    int n = pipe(pipefd);
    if(n < 0) return 1;

    // cout<<"pipefd[0]:"<<pipefd[0]<<",pipefd[1]:"<<pipefd[1]<<endl;

    //child-> w ,father-> r
    pid_t id = fork();
    if(id < 0) return 2;
    if(id == 0)
    {
        //child
        close(pipefd[0]);
        
        //IPC code
        Writer(pipefd[1]);        
        close(pipefd[1]);
        exit(0);
    }
    //father
    close(pipefd[1]);

    //IPC code
    Reader(pipefd[0]);
    
    pid_t rid = waitpid(id,nullptr,0);
    if(rid < 0) return 3;

    close(pipefd[0]);
    return 0;
}

